package com.hiss.basic.starter.mybatis.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hiss.basic.starter.core.utils.ServletUtils;
import com.mybatisflex.core.paginate.Page;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PageUtils {

    public static final String PAGE_FIELD = "pageNumber";

    public static final String SIZE_FIELD = "pageSize";

    public static final String TOTAL_FIELD = "totalRow";

    public static Page getPage() {
        try {
            HttpServletRequest request = ServletUtils.getRequest();
            if (ObjectUtil.isNotNull(request)) {
                Page page = new Page();
                String pageNumber = request.getParameter(PAGE_FIELD);
                if (StrUtil.isNotBlank(pageNumber)) {
                    page.setPageNumber(Integer.valueOf(pageNumber));
                }
                String pageSize = request.getParameter(SIZE_FIELD);
                if (StrUtil.isNotBlank(pageSize)) {
                    page.setPageSize(Integer.valueOf(pageSize));
                }
                // 非必须值，若传入该值，mybatis-flex 则不再去查询总数据量（若传入小于 0 的数值，也会去查询总量）。
                String totalRow = request.getParameter(TOTAL_FIELD);
                if (StrUtil.isNotBlank(totalRow)) {
                    page.setTotalRow(Integer.valueOf(totalRow));
                }
                return page;
            }
        } catch (Exception e) {
            log.warn("Get pagination parameter exceptions", e);
        }
        return new Page();
    }

    public static Page getEmptyPage() {
        Page page = new Page();
        page.setTotalRow(0);
        page.setTotalPage(0);
        return page;
    }
}
